/**
 * @author EasonChan
 *
 * Nov 17, 2010
 */
package com.musicgeek.biz.user;

import java.util.Map;

import javax.servlet.http.Cookie;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.musicgeek.biz.util.UserSecurityUtil;
import com.musicgeek.dao.User;
import com.musicgeek.dao.UserDao;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.ValidationAware;

public class Login extends ActionSupport implements SessionAware,
		ModelDriven<User>, ValidationAware {
	private static final long serialVersionUID = -2561852025743647934L;

	@Override
	public String execute() throws Exception {
		String name = getModel().getName();
		if (rememberMe) {
			String password = getModel().getPassword();
			if (UserDao.isUserExist(name)) {
				if (UserDao.validateUser(name, password)) {
					addLoginTokenToCookie(name, password);
				} else {
					addFieldError("user.password", "aaa");
					return INPUT;
				}
			} else {
				addFieldError("user.name", "aa");
				return INPUT;
			}
		}
		ServletActionContext.getRequest().getSession()
				.setAttribute(User.USER, name);
		return SUCCESS;
	}

	private void addLoginTokenToCookie(String name, String password) {
		String loginToken = UserSecurityUtil.generateLoginToken(name, password);
		Cookie cookie = new Cookie("login_token", loginToken);
		cookie.setMaxAge(24 * 3600 * 30);
		cookie.setPath("/");
		ServletActionContext.getResponse().addCookie(cookie);
	}

	@Override
	public void validate() {
		String name = user.getName().toLowerCase();
		final String userNameRegex = "^[a-z0-9_-]{3,16}$";
		if (!name.matches(userNameRegex))
			addFieldError("user.name", "aaa");
	}

	private User user = new User();
	private Map<String, Object> session;
	private boolean rememberMe;

	public boolean isRememberMe() {
		return rememberMe;
	}

	public void setRememberMe(boolean rememberMe) {
		this.rememberMe = rememberMe;
	}

	@Override
	public User getModel() {
		return user;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public Map<String, Object> getSession() {
		return session;
	}
}
